<!--//资源首页-->
<script setup>
import { ArrowRight, ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { userStore } from "~/composables/useUserStore";
import { useRoute } from "vue-router";
import requester from "~/utils/request";
import { baseURL } from "~/utils/request";
import { ElMessage } from "element-plus";

const router = useRoute()
const store = userStore()

const productId = router.params.id

const state = reactive({
  info: "",
  // 是否显示展开
  isShowOpen: false,

  accreditCodeTemp: '',
  accreditCode: '',
  zhekouPrice: '',
  orderCode: '',
  payUrl: '',
  isUse: false,
  showOrder: false,
  // 订单价格列表
  orderArr: [],
  // 当前订单价格选择
  currentOrderIndex: 0,
  // 是否打开推荐码
  isUseCode: false,
  // 评论
  comment: ""
})

const isOpen = ref(false)
const comment = ref()
const commentCon = ref(null);

async function scrollToComment() {
  await nextTick(); // 等待 DOM 更新完成
  if (commentCon.value) {
    const rect = commentCon.value.getBoundingClientRect();
    window.scrollTo({
      top: rect.top + window.pageYOffset - 80,
      behavior: 'smooth'
    });
  }
}
const productDesc = ref(null)
//获取商品信息
function getProduct() {
  const param = {
    productId: productId,
  }
  if (store.token.userCode) {
    param.userCode = store.token.userCode
  }
  requester.post('/api/product/getProduct', param).then((res) => {
    if (res.code == 200) {
      state.info = res.data
      //增加SEO
      useHead({
        title: '资源详情',
        titleTemplate: state.info.productName + ' - 资源详情',
        meta: [
          { hid: 'keywords', name: 'keywords', content: '资源' }
        ]
      })
      state.orderArr = [
        {
          desc: "基础版",
          name: "源码下载",
          price: state.info.priceCurrentPrice,
          buyType: "1"
        },
        {
          desc: "进阶版",
          name: "源码下载+远程部署",
          price: state.info.priceDeploy,
          buyType: "2"
        },
        {
          desc: "高阶版",
          name: "源码下载+远程部署+技术指导",
          price: state.info.priceGuide,
          buyType: "3"
        },
      ]
      nextTick(() => {
        try {
          let imgList = productDesc.value.querySelectorAll('img')

          imgList.forEach(element => {
            element.style.maxWidth = "100%"
          });
        } catch (error) {

        }

        if (productDesc.value.scrollHeight > 150) {
          state.isShowOpen = true
        }
      });
    }
  })
}

// 获取资源推荐
function getPushProduct() {
  const param = {
    "pageValidate": {
      "pageNo": 1,
      "pageSize": 8
    },
    "productType": "2",
  }
  requester.post('/api/product/pushProduct', param).then((res) => {
    if (res.code == 200) {
      state.articleList = res.data.lists
    }
  })
}

// 获取评论列表
function queryCommentList() {
  const param = {
    "businessId": productId,
    "pageValidate": {
      "pageNo": 1,
      "pageSize": 8
    },
    "userCode": store.token.userCode
  }
  if (!store.token.userCode) {
    delete param.userCode
  }
  requester.post('/api/comment/queryCommentList', param).then((res) => {
    if (res.code == 200) {
      state.commentList = res.data.lists
    }
  })
}

// 添加评论
function addComment() {
  const param = {
    "businessId": productId,
    "content": state.comment,
    "userCode": store.token.userCode
  }
  requester.post('/api/comment/addComment', param).then((res) => {
    if (res.code == 200) {
      state.comment = ""
      queryCommentList()
    }
  })
}

// 收益用户排行榜
function revenueRankList() {
  const param = {
    "pageValidate": {
      "pageNo": 1,
      "pageSize": 8
    },
  }
  requester.post('/api/account/revenueRankList', param).then((res) => {
    if (res.code == 200) {
      state.rankList = res.data.lists
    }
  })
}

onMounted(() => {
  revenueRankList()
  queryCommentList()
  getProduct()
  getPushProduct()
})


let orderTimer
// 获取支付二维码
function payOption() {
  if (!store.isLogin) {
    store.visiable = true
    return;
  }
  clearTimeout(orderTimer)
  if (state.info.priceCurrentPrice == '0.00') {
    downloadPack(1)
  } else {

    // 判断是否为移动端
    const isMobile = /Mobi|Android/i.test(navigator.userAgent);
    if (isMobile) {
      const currentUrl = window.location.href;  // 获取当前页面的完整URL
      // 使用Clipboard API将URL复制到剪贴板
      navigator.clipboard.writeText(currentUrl).then(() => {
        ElMessage.success('移动端不支持购买！已将链接复制到您手机中，请切换到电脑端！')
        return; // 在这里返回，结束函数
      }).catch(err => {
        console.error('Failed to copy: ', err);
        ElMessage.error('复制链接失败，请重试。'); // 提示用户复制失败
      });
      return; // 确保在移动端操作后不再继续执行下面的代码
    }


    state.showOrder = true;
    requester.post('/api/order/payOption', {
      "accreditCode": state.accreditCode,
      "buyType": state.orderArr[state.currentOrderIndex].buyType,
      "products": productId,
      "userCode": store.token.userCode
    }).then((res) => {
      if (res.code == 200) {
        state.payUrl = res.data.payUrl
        state.orderCode = res.data.orderCode
        state.accreditCode = ''
        state.isUse = true
        getOrder()
      } else {
        state.accreditCode = ''
        ElMessage.error(res.msg)
        state.showOrder = false
      }
    })

  }

}
function clr() {
  clearTimeout(orderTimer)
}
//获取订单
function getOrder() {
  if (!state.isUse) return
  requester.post('/api/order/getOrder', {
    orderCode: state.orderCode,
    userCode: store.token.userCode
  }).then((res) => {
    if (res.data.status == 0) {
      orderTimer = setTimeout(() => {
        getOrder()
      }, 3000)
    }
    if (res.data.status == -1) {
      clearTimeout(orderTimer)
      payOption()
    }
    if (res.data.status == 2) {
      clearTimeout(orderTimer)
      ElMessage.success('支付成功！')
      state.showOrder = false
      //跳转个人
      // navigateTo('/my?tabIndex=2')
      downloadPack(2)
    }
  })
}
function downloadPack(isFree) {
  var url
  var checkUrl
  if (isFree == 1) {
    checkUrl = `/api/file/downloadPackCheck?userCode=${store.token.userCode}&product=${productId}`
    url = `${baseURL}/api/file/downloadPackResEntity?userCode=${store.token.userCode}&product=${productId}`;
  } else {
    checkUrl = `/api/file/downloadPackCheck?userCode=${store.token.userCode}&orderCode=${state.orderCode}`
    url = `${baseURL}/api/file/downloadPackResEntity?userCode=${store.token.userCode}&orderCode=${state.orderCode}`;
  }
  requester.get(checkUrl).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.msg)
    } else {
      const a = document.createElement('a');
      a.href = url;
      a.download = state.info.packFiles[0].fileName
      document.body.appendChild(a);
      a.click(); // 模拟点击以下载
      document.body.removeChild(a); // 下载后移除链接
    }
  })
}

// 检测推荐码
function checkAccreditCode() {
  state.accreditCode = state.accreditCodeTemp
  requester.post('/api/user/checkAccreditCode', {
    accreditCode: state.accreditCode,
    // userCode: store.token.userCode
  }).then((res) => {
    if (res.code == 200) {
      clearTimeout(orderTimer)
      ElMessage.success('使用成功');
      state.zhekouPrice = state.info.priceAccreditRate
      state.orderArr.forEach(element => {
        element.zhekouPrice = (element.price * state.zhekouPrice).toFixed(2)
      });
      console.log(state)
      payOption()
    } else {
      state.accreditCode = ""
      ElMessage.error(res.msg);
    }
  })
}
// 退回
function cancelCode() {
  state.isUseCode = false;
  state.zhekouPrice = '';
  state.accreditCodeTemp = '';
  state.accreditCode = ''
}
</script>

<template>
  <myheader />
  <main class="main">
    <section class="bgCon">
      <div class="bgConChild bgConChild1"></div>
      <div class="bgConChild bgConChild2"></div>
      <div class="bgConChild bgConChild3"></div>
    </section>
    <div class="conWarp">
      <nav class="breadcrumbCon">
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/resources' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>文章详情</el-breadcrumb-item>
        </el-breadcrumb>
      </nav>
      <div class="conWarp-box">
        <article class="conWarp-left">

          <section class="detailCon">
            <div class="detailHeader">
              <div class="leftCon">
                <h1 class="leftTitle">
                  {{ state.info.productName }}
                </h1>
                <div class="detailInfo">
                  <section class="infoItem" v-if="state.info.fileSuffix">
                    文件格式：{{ state.info.fileSuffix }}
                  </section>
                  <section class="infoItem" v-if="state.info.fileSize">
                    文件大小：{{ state.info.fileSize }}
                  </section>
                  <section class="infoItem" v-if="state.info.createTime">
                    发布时间：{{ state.info.createTime }}
                  </section>
                </div>
              </div>
              <div class="rightCon">
                <div class="rightBtn" v-if="state.info.priceCurrentPrice != '0.00'" @click="payOption()">
                  ￥{{ state.info.priceCurrentPrice }}</div>
                <div class="rightBtn" v-else @click="payOption()">免费</div>
              </div>
            </div>

            <div class="detailBody">
              <div :class="[isOpen ? '' : 'isOpen', 'detailText']">
                <div v-if="state.info.productDesc" v-html="state.info.productDesc" ref="productDesc"></div>
                <div v-else>{{ state.info.productIntro }}</div>
              </div>
              <div class="detailOpen" @click="isOpen = !isOpen" v-if="state.isShowOpen">
                {{ isOpen ? '收起' : '展开' }}
                <el-icon style="margin-left: 5px;">
                  <ArrowUp v-if="isOpen" />
                  <ArrowDown v-else />
                </el-icon>
              </div>
            </div>

          </section>

          <section class="listCon">
            <div class="titleCon">
              <div class="titleText">
                资源推荐
              </div>
            </div>
            <resourceList :articleList="state.articleList" />
          </section>

          <section class="commentCon listCon" ref="commentCon">
            <div class="titleCon">
              <div class="titleText">
                资源评论
              </div>
            </div>

            <div class="commentMain">
              <div class="commentHeader" v-if="store.isLogin">
                <div class="avatarCenter">
                  <img class="user_avatar" v-if="store.token.imageUrl && store.token.imageUrl != ''"
                    :src="store.token.imageUrl" />
                  <div v-else class="header_avatar user_avatar">{{ store.token && store.token.nickName ?
                    store.token.nickName.slice(0, 1) : '' }}</div>
                </div>
                <div class="commentTextarea">
                  <el-input type="textarea" v-model="state.comment" placeholder="写下你想说的" :rows="3"
                    @keyup.enter="addComment()"></el-input>
                  <el-button type="primary" class="commentBtn" @click="addComment()">评论</el-button>
                </div>
              </div>
              <div v-if="!store.isLogin" class="noLogin">
                <el-button type="primary" class="commentBtn" @click="store.visiable = true">请登录</el-button>
              </div>

              <article class="commentBody">
                <section class="commentItem" v-for="item in state.commentList">
                  <div class="itemLeft">
                    <img :src="item.imageUrl" class="user_avatar">
                    <div class="content">
                      <h2 class="userName">
                        {{ item.nickName }}
                      </h2>
                      <p class="comment">
                        {{ item.content }}
                      </p>
                    </div>
                  </div>

                  <div class="date">
                    {{ item.createTime }}
                  </div>
                </section>
              </article>

            </div>
          </section>
        </article>


        <aside class="conWarp-right">
          <rightLogin />
          <creationCenter />
          <revenueUserRanking :rankList="state.rankList" />
          <!--          <videoAside />-->
        </aside>
      </div>
    </div>

    <el-dialog class="orderDialog" title="确认订单" v-model="state.showOrder" :z-index="2000" :before-close="clr()">
      <div class="orderBg">
        <div class="orderItems">
          <div :class="[state.currentOrderIndex == index ? 'active' : '', 'orderItem']"
            v-for="(item, index) in state.orderArr" v-show="item.price && item.price != '0.00'"
            @click="state.currentOrderIndex = index; payOption()">
            <div class="flex" style="justify-content: space-around;margin-bottom: 20px;">
              <div class="orderBottom">
                <div class="payCode">
                  <el-image :src="state.payUrl">
                    <template #error>
                      <div class="image-slot">
                        <el-icon class="is-loading">
                          <Loading />
                        </el-icon>
                        <span>Loading</span>
                      </div>
                    </template>
                  </el-image>
                </div>

                <div class="payItem">
                  <div class="flex wechatPay">
                    <img src="@/assets/details/wechat.png" alt="">
                    <p>支持微信扫码支付</p>
                  </div>
                </div>
              </div>
              <div>
                <div class="orderTag">
                  {{ item.desc }}
                </div>
                <div class="title">
                  {{ item.name }}
                </div>
                <div class="flex price">
                  <span style="font-size: 16px;">￥</span>
                  <span>{{ state.zhekouPrice ? item.zhekouPrice : item.price }}</span>
                </div>
              </div>


            </div>

            <div class="button">
              购买后立即下载资料
            </div>
          </div>
        </div>


      </div>
    </el-dialog>
  </main>

  <NewKefu @scrollToComment="scrollToComment" />
  <myFooter />
</template>

<style scoped lang="scss">
@import "./scss/index.scss";

.main {
  .conWarp {
    .conWarp-box {
      margin-top: 0
    }
  }
}

.breadcrumbCon {
  padding: 15px;
}

.detailCon {
  background-color: #ffffff;
  border-radius: 10px;

  .detailHeader {
    display: flex;
    justify-content: space-between;
    padding: 20px;
    border-radius: 10px 10px 0 0;
    border-bottom: 1px solid #E5E5E5;
    background: linear-gradient(180deg, #FFE9E2 0%, #FFFFFF 100%);

    .leftTitle {
      font-size: 26px;
      font-weight: 700;
      color: #333333;
      margin-top: 0;
    }

    .rightCon {
      margin-left: 10px;
      flex: none;
    }

    .detailInfo {
      display: flex;
      margin-top: 16px;
      flex-wrap: wrap;

      .infoItem {
        font-size: 14px;
        color: #4D8EFF;
        margin-right: 16px;
      }
    }

    .rightBtn {
      background: #444555;
      border-radius: 24px 24px 24px 24px;
      padding: 10px 30px;
      font-size: 18px;
      color: #FFC400;
      cursor: pointer;
    }
  }

  .detailBody {
    display: flex;
    padding: 20px;
    justify-content: space-between;

    .detailText {
      text-align: justify;
      line-height: 24px;

      p {
        img {
          max-width: 100% !important;
        }
      }

    }

    .isOpen {
      max-height: 150px;
      overflow: hidden;
    }

    .detailOpen {
      flex: none;
      color: #70A3FF;
      margin-left: 10px;
      display: flex;
      align-items: baseline;
      cursor: pointer;
    }
  }
}

.listCon {
  margin-top: $conTop;

  .titleCon {
    padding: 22px;
    padding-bottom: 0;

    .titleText {
      padding-bottom: 22px;
      border-bottom: 1px solid #E5E5E5;
    }
  }

  .commentMain {
    padding: 28px 22px;

    .header_avatar {
      position: relative;
      line-height: 35px;
      text-align: center;
      background: #1684fc;
      color: #fff;
    }

    .user_avatar {
      border-radius: 50%;
      width: 40px;
      height: 40px;
      font-size: 16px;
      line-height: 40px;
    }

    .commentHeader {
      display: flex;

      .commentTextarea {
        width: 100%;
        text-align: right;
      }

      .commentBtn {
        margin-top: 10px;
        border-radius: 20px;
        width: 80px;
        background: #488BFF;
      }

      .avatarCenter {
        margin-right: 20px;
      }

    }

    .noLogin {
      padding: 20px;
      display: flex;
      justify-content: center;
      width: 100%;
    }

    .commentBody {
      margin-top: 20px;

      .commentItem {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .user_avatar {
          margin-right: 30px;
        }

        .itemLeft {
          display: flex;
          align-items: center;

          .userName {
            font-weight: 500;
            font-size: 18px;
            color: #333333;
            margin-bottom: 5px
          }

          .comment {
            font-weight: 400;
            font-size: 14px;
            color: #999999;
          }
        }

        .date {
          font-weight: 400;
          font-size: 14px;
          color: #999999;
        }
      }
    }

    .commentItem+.commentItem {
      margin-top: 30px
    }
  }
}

@media screen and (max-width:768px) {
  .detailCon {
    .detailHeader {
      align-items: center;

      .detailInfo {
        margin-top: 10px;

        .infoItem {
          font-size: 12px;
          margin-top: 5px;
        }
      }

      .rightCon {
        flex: none;

        .rightBtn {
          padding: 7px 10px;
          font-size: 14px;
        }
      }

    }

    .detailBody {
      padding-top: 10px
    }
  }

  .listCon {
    .titleCon {
      padding: 10px;
      padding-bottom: 0;

      .titleText {
        padding-bottom: 10px;
      }
    }
  }

}
</style>
